# coding=utf-8
'''
Created on 2017年12月12日

@author: hhl
'''
import json
import urllib
import requests



class QQClient():
    """QQ第三方登陆
    """
    def __init__(self):
        self.authorize = 'https://graph.qq.com/oauth2.0/authorize'
        self.token_url = 'https://graph.qq.com/oauth2.0/token'
        self.openid_url = 'https://graph.qq.com/oauth2.0/me'
        self.appid = '101444655'
        self.appkey = '771c7734c8b92c0265fcedb228043425'
        
    def dict2url(self, parms):
        parm_items = sorted(parms.items(), key=lambda d: d[0])
        parmlist = ["%s=%s"%item for item in parm_items]
        parm_str =  "&".join(parmlist)
        return parm_str
    
    def create_authorize_url(self, redirect_url):
        #授权链接
        parms = {'response_type':'code','client_id':self.appid,'redirect_uri':'',
                'display':'mobile', 'state':'jixieceshi'}
        parms['redirect_uri'] = urllib.quote(redirect_url)
        params_str = self.dict2url(parms)
        url = '%s?%s'%(self.authorize,params_str)
        return url
    
    def get_token_url(self,code,redirect_url):
        #构建获取token链接
        token_params = {'grant_type':'authorization_code','code':code,
                        'client_id':self.appid,
                        'client_secret':self.appkey,'redirect_uri':''}
        print 
        token_params['redirect_uri'] = urllib.quote(redirect_url)
        params_str = self.dict2url(token_params)
        url = '%s?%s'%(self.token_url,params_str)
        return url
    
    def get_token(self, code,redirect_url=''):
        get_token_url = self.get_token_url(code, redirect_url)
        result = requests.get(get_token_url)
        content = result.text 
        if '&' not in content:
            return ''
        s = content.split('&')
        s = s[0].split('=')
        return s[1]
    
    def get_qquser_openid(self,access_token):
        user_info_url = '%s?access_token=%s'%(self.openid_url,access_token)
        print user_info_url
        result = requests.get(user_info_url)
        content = result.text
        content = content.split('(')
        content = content[1].split(')')
        if 'openid' in content[0]:
            data = json.loads(content[0])
            return data
        else:
            return {}
        
    def get_userinfo(self,token,openid):
        url = 'https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s'%(token,self.appid,openid)
        print url
        result = requests.get(url)
        content = result.text
        print content
        data = json.loads(content)
        return data

qqclient = QQClient()    

if __name__ == '__main__':
    print  qqclient.get_userinfo('E11C43C526C09FFA425B01912B6E861C','89FB2EB9568EACDBF2C04CDCB111B907')